GameLayer = function()
{
	Sprite.call(this);
	this.mouseChildren = false ;
	this.prevTime = 0 ;
	
	this.apples = [];
	
	this.hero = new Hero();
	this.hero.setY( FlashCore.stage.getStageHeight()-this.hero.getHeight()-40 );
	this.addChild(this.hero);
};
FLASH.extend(GameLayer,Sprite);

GameLayer.prototype.reset = function()
{
	this.stopGame();
	var apple ;
	for( var i =0  ; i<this.apples.length ; ++i)
	{
		apple = this.apples[i];
		this.removeChild(apple , true );
	};
	this.apples = [] ;
};

GameLayer.prototype.startGame = function()
{
	this.addEventListener( Event.ENTER_FRAME , this.update );
};

GameLayer.prototype.stopGame = function()
{
	this.removeEventListener( Event.ENTER_FRAME , this.update );
};

GameLayer.prototype.update = function(e)
{
	var target=  e.getTarget();
	var apple ;
	//在一定的时间内添加一个苹果
	if(GlobalUtil.getTimer()-target.prevTime>20)
	{
		target.prevTime = GlobalUtil.getTimer() ;
		apple = AppleBase.randomCreateApple() ;
		target.apples.push(apple);
		target.addChild( apple );
	}
	
	//英雄位置跟随鼠标移动，添加一点缓动效果
	var offset = (target.getStage().getMouseX()-target.hero.getWidth()*0.5+20 - target.hero.getX() )*0.15 ;
	target.hero.setX( target.hero.getX()+offset  );
	
	var appleRect = new Rectangle();
	var heroRect = target.hero.collision.clone();
	heroRect.x += target.hero.getX();
	heroRect. y += target.hero.getY();
	for( var i =0  ; i<target.apples.length ; ++i)
	{
		apple = target.apples[i];
		apple.setY( apple.getY()+apple.speed );
		if(apple.getY()>640)
		{
			//如果超出屏幕下面，就移除
			target.removeChild(apple , true );
			target.apples.splice( i , 1 );
			i-- ;
		}
		else if(apple.getY()>target.hero.getY())
		{
			appleRect.x = apple.getX()+10 ;
			appleRect.y =  apple.getY()+10 ;
			appleRect.width = apple.getWidth()-10 ;
			appleRect.height =  apple.getHeight()-10 ;
			if( appleRect.intersects(heroRect)){
				//碰撞成功
				target.removeChild(apple , true);
				target.apples.splice( i , 1 );
				GlobalDispatcher.getInstance().dispatchEvent( new ScoreEvent(ScoreEvent.SCORE_CHANGE , apple.score ));
				i-- ;
			}
		}
	}
};